import 'package:flutter/material.dart';
import '../../core/elegance_theme.dart';

/// 表格列定义
class ETableColumn<T> {
  /// 创建ETableColumn
  const ETableColumn({
    required this.prop,
    required this.label,
    this.width,
    this.minWidth,
    this.fixed = false,
    this.fixedLeft = false,
    this.fixedRight = false,
    this.sortable = false,
    this.sortMethod,
    this.formatter,
    this.renderHeader,
    this.render,
    this.resizable = false,
    this.showOverflowTooltip = true,
  });

  /// 列数据字段名
  final String prop;
  
  /// 列标题
  final String label;
  
  /// 列宽度
  final double? width;
  
  /// 列最小宽度
  final double? minWidth;
  
  /// 是否固定列（兼容旧版本）
  final bool fixed;
  
  /// 是否固定在左侧
  final bool fixedLeft;
  
  /// 是否固定在右侧
  final bool fixedRight;
  
  /// 是否可排序
  final bool sortable;
  
  /// 排序方法
  final int Function(T, T)? sortMethod;
  
  /// 格式化函数
  final String Function(dynamic)? formatter;
  
  /// 自定义表头渲染方法
  final Widget Function(BuildContext)? renderHeader;
  
  /// 自定义内容渲染方法
  final Widget Function(BuildContext, T, int)? render;
  
  /// 是否可调整列宽
  final bool resizable;
  
  /// 内容过长时是否显示 tooltip
  final bool showOverflowTooltip;
}

/// 表格排序方向
enum ETableSortDirection {
  /// 升序
  ascending,
  
  /// 降序
  descending,
  
  /// 无排序
  none,
}

/// 表格选择类型
enum ETableSelectionType {
  /// 单选
  single,
  
  /// 多选
  multiple,
}

/// 表格组件 - 基于Element Plus表格组件实现
class ETable<T> extends StatefulWidget {
  /// 创建ETable组件
  const ETable({
    super.key,
    required this.data,
    required this.columns,
    this.height,
    this.maxHeight,
    this.striped = false,
    this.border = false,
    this.showHeader = true,
    this.hoverable = true,
    this.rowKey,
    this.onRowClick,
    this.onRowDoubleClick,
    this.emptyText = '暂无数据',
    this.loading = false,
    // Element Plus 特有属性
    this.size,
    this.highlightCurrentRow = false,
    this.currentRowKey,
    this.selectionType,
    this.rowSelection,
    this.selectable,
    this.showSummary = false,
    this.sumText = '合计',
    this.summaryMethod,
    this.defaultSort,
    this.headerRowClassName,
    this.rowClassName,
    this.cellClassName,
  });

  /// 表格数据
  final List<T> data;
  
  /// 表格列定义
  final List<ETableColumn<T>> columns;
  
  /// 表格高度
  final double? height;
  
  /// 表格最大高度
  final double? maxHeight;
  
  /// 是否显示斑马纹
  final bool striped;
  
  /// 是否显示边框
  final bool border;
  
  /// 是否显示表头
  final bool showHeader;
  
  /// 是否支持鼠标悬停效果
  final bool hoverable;
  
  /// 行唯一标识属性名
  final String? rowKey;
  
  /// 行点击回调
  final Function(T, int)? onRowClick;
  
  /// 行双击回调
  final Function(T, int)? onRowDoubleClick;
  
  /// 空数据时的提示文本
  final String emptyText;
  
  /// 是否显示加载中状态
  final bool loading;
  
  /// 表格尺寸 (large, default, small)
  final String? size;
  
  /// 是否高亮当前行
  final bool highlightCurrentRow;
  
  /// 当前行的 key
  final dynamic currentRowKey;
  
  /// 选择类型
  final ETableSelectionType? selectionType;
  
  /// 行选中状态变化回调
  final Function(List<T> selectedRows)? rowSelection;
  
  /// 是否可选择某一行
  final bool Function(T, int)? selectable;
  
  /// 是否显示合计行
  final bool showSummary;
  
  /// 合计行文本
  final String sumText;
  
  /// 自定义合计方法
  final Map<String, dynamic> Function(List<T> rows)? summaryMethod;
  
  /// 默认排序规则
  final Map<String, ETableSortDirection>? defaultSort;
  
  /// 表头行的类名
  final String Function()? headerRowClassName;
  
  /// 行的类名
  final String Function(T, int)? rowClassName;
  
  /// 单元格的类名
  final String Function(T, int, String)? cellClassName;

  @override
  _ETableState<T> createState() => _ETableState<T>();
}

class _ETableState<T> extends State<ETable<T>> {
  /// 当前排序列
  String? _sortColumn;
  
  /// 当前排序方向
  ETableSortDirection _sortDirection = ETableSortDirection.none;
  
  /// 当前悬停的行索引
  int? _hoveredRowIndex;
  
  /// 当前选中的行索引
  int? _highlightedRowIndex;
  
  /// 选中的行数据
  final Set<T> _selectedRows = {};
  
  @override
  void initState() {
    super.initState();
    
    // 初始化默认排序
    if (widget.defaultSort != null && widget.defaultSort!.isNotEmpty) {
      final entry = widget.defaultSort!.entries.first;
      _sortColumn = entry.key;
      _sortDirection = entry.value;
    }
    
    // 初始化高亮行
    if (widget.highlightCurrentRow && widget.currentRowKey != null) {
      _updateHighlightedRow();
    }
  }
  
  @override
  void didUpdateWidget(covariant ETable<T> oldWidget) {
    super.didUpdateWidget(oldWidget);
    
    // 更新高亮行
    if (widget.highlightCurrentRow && 
        widget.currentRowKey != oldWidget.currentRowKey) {
      _updateHighlightedRow();
    }
  }
  
  /// 更新高亮行
  void _updateHighlightedRow() {
    if (widget.data.isEmpty || widget.rowKey == null) return;
    
    final index = widget.data.indexWhere((item) {
      final rowValue = _getPropValue(item, widget.rowKey!);
      return rowValue == widget.currentRowKey;
    });
    
    setState(() {
      _highlightedRowIndex = index >= 0 ? index : null;
    });
  }
  
  /// 获取行数据的指定属性值
  dynamic _getPropValue(T item, String prop) {
    // 尝试通过Map获取属性值
    if (item is Map) {
      return item[prop];
    }
    
    // 尝试通过反射获取属性值
    // 在实际使用中，可能需要根据具体数据类型进行调整
    try {
      final mirror = item.runtimeType;
      // 简化实现，实际项目中可以使用 dart:mirrors 包
      return null;
    } catch (e) {
      return null;
    }
  }
  
  /// 处理表头点击（排序）
  void _handleHeaderClick(String prop) {
    final column = widget.columns.firstWhere(
      (c) => c.prop == prop, 
      orElse: () => widget.columns.first
    );
    
    if (!column.sortable) {
      return;
    }
    
    setState(() {
      if (_sortColumn == prop) {
        // 如果点击的是当前排序列，则切换排序方向
        if (_sortDirection == ETableSortDirection.ascending) {
          _sortDirection = ETableSortDirection.descending;
        } else if (_sortDirection == ETableSortDirection.descending) {
          _sortDirection = ETableSortDirection.none;
          _sortColumn = null;
        } else {
          _sortDirection = ETableSortDirection.ascending;
        }
      } else {
        // 如果点击的是新的列，则设置为升序排序
        _sortColumn = prop;
        _sortDirection = ETableSortDirection.ascending;
      }
    });
  }
  
  /// 处理行选择
  void _handleRowSelection(T row, int index) {
    if (widget.selectionType == null || widget.rowSelection == null) return;
    
    if (widget.selectable != null && !widget.selectable!(row, index)) {
      return;
    }
    
    setState(() {
      if (widget.selectionType == ETableSelectionType.single) {
        _selectedRows.clear();
        _selectedRows.add(row);
      } else {
        if (_selectedRows.contains(row)) {
          _selectedRows.remove(row);
        } else {
          _selectedRows.add(row);
        }
      }
      
      widget.rowSelection!(List.from(_selectedRows));
    });
  }
  
  /// 获取排序后的数据
  List<T> _getSortedData() {
    if (_sortColumn == null || _sortDirection == ETableSortDirection.none) {
      return widget.data;
    }
    
    final column = widget.columns.firstWhere(
      (c) => c.prop == _sortColumn,
      orElse: () => widget.columns.first
    );
    final List<T> sortedData = List.from(widget.data);
    
    sortedData.sort((a, b) {
      int result = 0;
      
      if (column.sortMethod != null) {
        // 使用自定义排序方法
        result = column.sortMethod!(a, b);
      } else {
        // 使用默认排序方法
        final valueA = _getPropValue(a, _sortColumn!);
        final valueB = _getPropValue(b, _sortColumn!);
        
        if (valueA != null && valueB != null) {
          if (valueA is Comparable && valueB is Comparable) {
            result = valueA.compareTo(valueB);
          }
        } else if (valueA == null && valueB != null) {
          result = -1;
        } else if (valueA != null && valueB == null) {
          result = 1;
        }
      }
      
      // 根据排序方向调整结果
      if (_sortDirection == ETableSortDirection.descending) {
        result = -result;
      }
      
      return result;
    });
    
    return sortedData;
  }
  
  /// 获取行高
  double _getRowHeight() {
    switch (widget.size) {
      case 'large':
        return 48.0;
      case 'small':
        return 36.0;
      default:
        return 42.0;
    }
  }
  
  /// 构建表头
  Widget _buildHeader() {
    if (!widget.showHeader) {
      return Container();
    }
    
    final theme = EleganceTheme.of(context);
    final rowHeight = _getRowHeight();
    
    return Container(
      height: rowHeight,
      decoration: BoxDecoration(
        color: theme.surfaceColor,
        border: widget.border 
          ? Border(
              top: BorderSide(color: theme.borderColor),
              bottom: BorderSide(color: theme.borderColor)
            ) 
          : null,
      ),
      child: Row(
        children: widget.columns.map((column) {
          return _buildHeaderCell(column, theme, rowHeight);
        }).toList(),
      ),
    );
  }
  
  /// 构建表头单元格
  Widget _buildHeaderCell(
    ETableColumn<T> column, 
    EleganceThemeData theme, 
    double rowHeight
  ) {
    final isFixed = column.fixed || column.fixedLeft || column.fixedRight;
    
    return Container(
      width: column.width ?? column.minWidth ?? 120.0,
      constraints: column.minWidth != null 
        ? BoxConstraints(minWidth: column.minWidth!) 
        : null,
      padding: const EdgeInsets.symmetric(horizontal: 12.0),
      decoration: BoxDecoration(
        border: widget.border 
          ? Border(right: BorderSide(color: theme.borderColor)) 
          : null,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          column.renderHeader != null
            ? column.renderHeader!(context)
            : Text(
                column.label,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: theme.textPrimaryColor,
                ),
              ),
          if (column.sortable) ...[
            GestureDetector(
              onTap: () => _handleHeaderClick(column.prop),
              child: _buildSortIcon(column.prop),
            ),
          ],
          if (column.resizable) ...[
            // 简化实现，实际项目中可以添加调整列宽的功能
            const SizedBox(width: 10),
          ],
        ],
      ),
    );
  }
  
  /// 构建排序图标
  Widget _buildSortIcon(String prop) {
    if (_sortColumn != prop) {
      return const Icon(Icons.unfold_more, size: 14.0, color: Colors.grey);
    }
    
    return Icon(
      _sortDirection == ETableSortDirection.ascending 
        ? Icons.arrow_upward 
        : Icons.arrow_downward,
      size: 14.0,
      color: EleganceTheme.of(context).primaryColor,
    );
  }
  
  /// 构建表格内容
  Widget _buildBody() {
    final theme = EleganceTheme.of(context);
    final sortedData = _getSortedData();
    
    if (widget.loading) {
      return _buildLoadingState(theme);
    }
    
    if (sortedData.isEmpty) {
      return _buildEmptyState(theme);
    }
    
    final rowHeight = _getRowHeight();
    final showSelection = widget.selectionType != null;
    
    final List<Widget> rows = sortedData.asMap().entries.map((entry) {
      final index = entry.key;
      final item = entry.value;
      final isSelected = _selectedRows.contains(item);
      
      return MouseRegion(
        onEnter: (_) {
          if (widget.hoverable) {
            setState(() {
              _hoveredRowIndex = index;
            });
          }
        },
        onExit: (_) {
          if (widget.hoverable) {
            setState(() {
              _hoveredRowIndex = null;
            });
          }
        },
        child: GestureDetector(
          onTap: () {
            if (widget.onRowClick != null) {
              widget.onRowClick!(item, index);
            }
          },
          onDoubleTap: widget.onRowDoubleClick != null 
            ? () => widget.onRowDoubleClick!(item, index) 
            : null,
          child: Container(
            height: rowHeight,
            decoration: BoxDecoration(
              color: _getRowBackgroundColor(index, item, theme),
              border: widget.border 
                ? Border(bottom: BorderSide(color: theme.borderColor)) 
                : null,
            ),
            child: Row(
              children: [
                // 选择列
                if (showSelection) ...[
                  Container(
                    width: 40,
                    alignment: Alignment.center,
                    child: Checkbox(
                      value: isSelected,
                      onChanged: (widget.selectable == null || 
                           widget.selectable!(item, index)) 
                        ? (_) => _handleRowSelection(item, index)
                        : null,
                      activeColor: theme.primaryColor,
                    ),
                  ),
                ],
                // 数据列
                ...widget.columns.map((column) {
                  return _buildBodyCell(item, index, column, theme);
                }).toList(),
              ],
            ),
          ),
        ),
      );
    }).toList();
    
    // 添加合计行
    if (widget.showSummary) {
      rows.add(_buildSummaryRow(theme, rowHeight));
    }
    
    return Column(children: rows);
  }
  
  /// 获取行背景色
  Color _getRowBackgroundColor(
    int index, 
    T item, 
    EleganceThemeData theme
  ) {
    // 检查是否可选中
    final canSelect = widget.selectable == null || widget.selectable!(item, index);
    
    // 检查是否为当前高亮行
    final isHighlighted = widget.highlightCurrentRow && 
                         _highlightedRowIndex == index;
    
    // 检查是否为悬停行
    final isHovered = widget.hoverable && _hoveredRowIndex == index;
    
    // 检查是否为选中行
    final isSelected = _selectedRows.contains(item);
    
    // 检查是否为斑马纹行
    final isStriped = widget.striped && index.isOdd;
    
    if (isSelected && canSelect) {
      return Colors.blue.shade100;
    } else if (isHighlighted) {
      return Colors.grey.shade200;
    } else if (isHovered) {
      return Colors.blue.shade50;
    } else if (isStriped) {
      return Colors.grey.shade50;
    }
    
    return Colors.white;
  }
  
  /// 构建内容单元格
  Widget _buildBodyCell(
    T item, 
    int index, 
    ETableColumn<T> column, 
    EleganceThemeData theme
  ) {
    Widget content;
    
    if (column.render != null) {
      // 使用自定义渲染方法
      content = column.render!(context, item, index);
    } else {
      // 使用默认文本渲染
      dynamic value = _getPropValue(item, column.prop);
      
      // 使用格式化函数
      if (column.formatter != null && value != null) {
        value = column.formatter!(value);
      }
      
      content = Text(
        value?.toString() ?? '',
        style: TextStyle(color: theme.textRegularColor),
        overflow: column.showOverflowTooltip ? TextOverflow.ellipsis : null,
      );
      
      // 添加 tooltip
      if (column.showOverflowTooltip) {
        content = Tooltip(
          message: value?.toString() ?? '',
          child: content,
        );
      }
    }
    
    return Container(
      width: column.width ?? column.minWidth ?? 120.0,
      constraints: column.minWidth != null 
        ? BoxConstraints(minWidth: column.minWidth!) 
        : null,
      padding: const EdgeInsets.symmetric(horizontal: 12.0),
      decoration: widget.border 
        ? BoxDecoration(
            border: Border(right: BorderSide(color: theme.borderColor)),
          ) 
        : null,
      alignment: Alignment.centerLeft,
      child: content,
    );
  }
  
  /// 构建合计行
  Widget _buildSummaryRow(
    EleganceThemeData theme, 
    double rowHeight
  ) {
    // 合计数据
    Map<String, dynamic> summaryData = {};
    
    if (widget.summaryMethod != null) {
      // 使用自定义合计方法
      summaryData = widget.summaryMethod!(widget.data);
    } else {
      // 简单的合计实现（对数字进行求和）
      for (var column in widget.columns) {
        double sum = 0.0;
        bool hasNumber = false;
        
        for (var item in widget.data) {
          final value = _getPropValue(item, column.prop);
          if (value is num) {
            sum += value;
            hasNumber = true;
          }
        }
        
        if (hasNumber) {
          summaryData[column.prop] = sum;
        }
      }
    }
    
    return Container(
      height: rowHeight,
      decoration: BoxDecoration(
        color: theme.surfaceColor,
        border: widget.border 
          ? Border(top: BorderSide(color: theme.borderColor, width: 2)) 
          : null,
      ),
      child: Row(
        children: [
          // 选择列占位
          if (widget.selectionType != null) ...[
            const SizedBox(width: 40),
          ],
          // 合计文本
          Container(
            width: widget.columns.first.width ?? widget.columns.first.minWidth ?? 120.0,
            padding: const EdgeInsets.symmetric(horizontal: 12.0),
            decoration: widget.border 
              ? BoxDecoration(
                  border: Border(right: BorderSide(color: theme.borderColor)),
                ) 
              : null,
            alignment: Alignment.centerLeft,
            child: Text(
              widget.sumText,
              style: TextStyle(
                fontWeight: FontWeight.bold,
                color: theme.textPrimaryColor,
              ),
            ),
          ),
          // 合计数据列
          ...widget.columns.skip(1).map((column) {
            final value = summaryData[column.prop];
            
            return Container(
              width: column.width ?? column.minWidth ?? 120.0,
              padding: const EdgeInsets.symmetric(horizontal: 12.0),
              decoration: widget.border 
                ? BoxDecoration(
                    border: Border(right: BorderSide(color: theme.borderColor)),
                  ) 
                : null,
              alignment: Alignment.centerLeft,
              child: Text(
                value?.toString() ?? '',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: theme.textPrimaryColor,
                ),
              ),
            );
          }).toList(),
        ],
      ),
    );
  }
  
  /// 构建加载中状态
  Widget _buildLoadingState(EleganceThemeData theme) {
    final height = widget.height ?? 300.0;
    
    return Container(
      height: height,
      alignment: Alignment.center,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(color: theme.primaryColor),
          const SizedBox(height: 12.0),
          Text('加载中...', style: TextStyle(color: theme.textRegularColor)),
        ],
      ),
    );
  }
  
  /// 构建空数据状态
  Widget _buildEmptyState(EleganceThemeData theme) {
    final height = widget.height ?? 300.0;
    
    return Container(
      height: height,
      alignment: Alignment.center,
      child: Text(
        widget.emptyText,
        style: TextStyle(
          color: theme.textPlaceholderColor,
          fontSize: 16.0,
        ),
      ),
    );
  }
  
  @override
  Widget build(BuildContext context) {
    final theme = EleganceTheme.of(context);
    
    // 根据尺寸调整内边距
    final padding = widget.size == 'small' 
      ? const EdgeInsets.all(8.0) 
      : widget.size == 'large'
        ? const EdgeInsets.all(16.0)
        : const EdgeInsets.all(12.0);
    
    // 构建表格内容
    Widget tableContent = Column(
      children: [
        _buildHeader(),
        _buildBody(),
      ],
    );
    
    // 处理高度限制
    Widget tableWithHeight;
    if (widget.maxHeight != null && widget.height == null) {
      tableWithHeight = ConstrainedBox(
        constraints: BoxConstraints(maxHeight: widget.maxHeight!),
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: tableContent,
        ),
      );
    } else if (widget.height != null) {
      tableWithHeight = SizedBox(
        height: widget.height,
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: tableContent,
        ),
      );
    } else {
      tableWithHeight = tableContent;
    }
    
    // 外层容器
    return Container(
      decoration: BoxDecoration(
        border: widget.border 
          ? Border(
              left: BorderSide(color: theme.borderColor),
              right: BorderSide(color: theme.borderColor),
              bottom: BorderSide(color: theme.borderColor)
            )
          : null,
        borderRadius: BorderRadius.circular(theme.borderRadius),
      ),
      padding: padding,
      child: tableWithHeight,
    );
  }
}